package com.qianfeng.smartdevices.service.impl;

import com.qianfeng.smartdevices.cache.RoleMenuCache;
import com.qianfeng.smartdevices.dto.ResultCode;
import com.qianfeng.smartdevices.event.RoleMenuChangeEvent;
import com.qianfeng.smartdevices.exceptions.AddErrorException;
import com.qianfeng.smartdevices.mapper.RoleMenuMapper;
import com.qianfeng.smartdevices.pojo.CheckStatus;
import com.qianfeng.smartdevices.pojo.RoleMenu;
import com.qianfeng.smartdevices.service.RoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional
public class RoleMenuServiceImpl implements RoleMenuService {

    private RoleMenuMapper roleMenuMapper;

    private RoleMenuCache roleMenuCache;
    private ApplicationContext context;
    @Autowired
    public void setRoleMenuCache(RoleMenuCache roleMenuCache) {
        this.roleMenuCache = roleMenuCache;
    }
    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setRoleMenuMapper(RoleMenuMapper roleMenuMapper) {
        this.roleMenuMapper = roleMenuMapper;
    }

    @Override
    public void addRoleMenu(RoleMenu roleMenu) {
        if (roleMenu.isNull(CheckStatus.ADD)) {
            throw new AddErrorException("添加数据不能为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        roleMenuMapper.addRoleMenu(roleMenu);

        context.publishEvent(new RoleMenuChangeEvent());
    }

    @Override
    public List<RoleMenu> findALLRoleMenu() {
//        return roleMenuMapper.findALLRoleMenu();
        return roleMenuCache.getAllData();
    }

    @Override
    public void updateRoleMenu(Long roleId, Long menuId, Long id) {
        roleMenuMapper.updateRoleMenu(roleId,menuId,id);
        context.publishEvent(new RoleMenuChangeEvent());
    }
}
